const apiKey = "1fdd09312314cb1182a7b97699a3dd84"; // 🔑 Replace with your OpenWeather API key const cityInput = document.getElementById("cityInput"); const searchBtn = document.getElementById("searchBtn"); const cityName = document.getElementById("cityName"); const temperature = document.getElementById("temperature"); const description = document.getElementById("description"); const humidity = document.getElementById("humidity"); const weatherIcon = document.getElementById("weatherIcon"); const weatherBox = document.getElementById("weatherBox"); const errorMsg = document.getElementById("errorMsg"); const forecastBox = document.getElementById("forecastBox"); const forecastCards = document.getElementById("forecastCards"); const loader = document.getElementById("loader"); const unitBtn = document.getElementById("unitBtn"); const historySelect = document.getElementById("historySelect"); const clearHistoryBtn = document.getElementById("clearHistoryBtn"); let unit = "metric"; // default Celsius let searchHistory = JSON.parse(localStorage.getItem("searchHistory")) || []; // Show loader function showLoader() { loader.classList.remove("hidden"); } // Hide loader function hideLoader() { loader.classList.add("hidden"); } // Save city to history function saveToHistory(city) { city = city.trim(); if (!city || searchHistory.includes(city)) return; searchHistory.unshift(city); if (searchHistory.length > 5) searchHistory.pop(); localStorage.setItem("searchHistory", JSON.stringify(searchHistory)); updateHistoryDropdown(); } // Update dropdown function updateHistoryDropdown() { historySelect.innerHTML = ``; searchHistory.forEach(city => { const option = document.createElement("option"); option.value = city; option.textContent = city; historySelect.appendChild(option); }); } // Fetch weather by city async function fetchWeather(city) { const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=${unit}`; showLoader(); try { const response = await fetch(url); if (!response.ok) throw new Error("City not found"); const data = await response.json(); showWeather(data); fetchForecast(city); saveToHistory(city); } catch { weatherBox.classList.add("hidden"); errorMsg.classList.remove("hidden"); forecastBox.classList.add("hidden"); } finally { hideLoader(); } } // Fetch forecast async function fetchForecast(city) { const url = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}&units=${unit}`; try { const response = await fetch(url); if (!response.ok) throw new Error("Forecast not found"); const data = await response.json(); showForecast(data); } catch { forecastBox.classList.add("hidden"); } } // Show weather function showWeather(data) { const tempUnit = unit === "metric" ? "°C" : "°F"; cityName.textContent = `${data.name}, ${data.sys.country}`; temperature.textContent = `🌡 ${data.main.temp.toFixed(1)}${tempUnit}`; description.textContent = `🌥 ${data.weather[0].description}`; humidity.textContent = `💧 Humidity: ${data.main.humidity}%`; weatherIcon.src = `https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`; weatherBox.classList.remove("hidden"); errorMsg.classList.add("hidden"); } // Show forecast function showForecast(data) { forecastCards.innerHTML = ""; const dailyData = {}; const tempUnit = unit === "metric" ? "°C" : "°F"; data.list.forEach(item => { const date = item.dt_txt.split(" ")[0]; const time = item.dt_txt.split(" ")[1]; if (time === "12:00:00" && !dailyData[date]) { dailyData[date] = item; } }); Object.keys(dailyData).forEach(date => { const forecast = dailyData[date]; const card = document.createElement("div"); card.classList.add("forecast-card"); const options = { weekday: "short" }; const dayName = new Date(date).toLocaleDateString(undefined, options); card.innerHTML = `
${dayName}
${forecast.main.temp.toFixed(1)}${tempUnit}
${forecast.weather[0].main}
`; forecastCards.appendChild(card); }); forecastBox.classList.remove("hidden"); } // Events searchBtn.addEventListener("click", () => { const city = cityInput.value.trim(); if (city) fetchWeather(city); }); cityInput.addEventListener("keypress", e => { if (e.key === "Enter") { const city = cityInput.value.trim(); if (city) fetchWeather(city); } }); unitBtn.addEventListener("click", () => { if (unit === "metric") { unit = "imperial"; unitBtn.textContent = "Switch to °C"; } else { unit = "metric"; unitBtn.textContent = "Switch to °F"; } const city = cityName.textContent.split(",")[0]; if (city) fetchWeather(city); }); historySelect.addEventListener("change", () => { const city = historySelect.value; if (city) fetchWeather(city); }); clearHistoryBtn.addEventListener("click", () => { searchHistory = []; localStorage.removeItem("searchHistory"); updateHistoryDropdown(); }); // Init updateHistoryDropdown();